//
//  GPXParser.m
//  Location
//
//  Created by Dylan on 2024/5/31.
//

#import "GPXParser.h"

@implementation GPXParser

- (NSArray<GPXWaypoint *> *)parseFileAtURL:(NSURL *)fileURL {
    self.waypoints = [NSMutableArray array];
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:fileURL];
    parser.delegate = self;
    [parser parse];
    return [self.waypoints copy];
}


- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict {
    self.currentElement = elementName;
    
    if ([elementName isEqualToString:@"wpt"]) {
        self.currentWaypoint = [[GPXWaypoint alloc] init];
        self.currentWaypoint.latitude = [attributeDict[@"lat"] doubleValue];
        self.currentWaypoint.longitude = [attributeDict[@"lon"] doubleValue];
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
    if ([self.currentElement isEqualToString:@"name"]) {
        self.currentWaypoint.name = string;
    } else if ([self.currentElement isEqualToString:@"time"]) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss'Z'";
        formatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
        self.currentWaypoint.time = [formatter dateFromString:string];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    if ([elementName isEqualToString:@"wpt"]) {
        [self.waypoints addObject:self.currentWaypoint];
        self.currentWaypoint = nil;
    }
}
@end
